<template>
  <div class="psqi-survey">
    <div class="header">
      <h1>{{ surveyConfig.title }}</h1>
      <p class="subtitle">{{ surveyConfig.subtitle }}</p>
      <div class="header-actions">
        <button @click="goToHome" class="home-btn">
          <span class="home-icon">🏠</span> {{ surveyConfig.ui.buttons.home }}
        </button>
        <button @click="showSettings = true" class="settings-btn">
          <span class="settings-icon">⚙️</span> {{ surveyConfig.ui.buttons.settings }}
        </button>
      </div>
    </div>

    <!-- 设置页面 -->
    <div class="settings-modal" v-if="showSettings">
      <div class="settings-content">
        <div class="settings-header">
          <h2>{{ surveyConfig.settings.title }}</h2>
          <button @click="closeSettings" class="close-btn">×</button>
        </div>

        <div class="settings-form">
          <div class="form-group">
            <label>问答编号：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.surveyId" placeholder="请输入问答编号（用于区分不同组的问卷）" maxlength="20">
            <p class="field-hint">编号用于区分不同组的问卷，建议使用如：PSQI001、SLEEP_A等格式</p>
          </div>
          <div class="form-group">
            <label>记录人姓名：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.name" placeholder="请输入记录人姓名">
          </div>
          <div class="form-group">
            <label>记录人职务/身份：<span class="required">*</span></label>
            <input type="text" v-model="recorderInfo.position" placeholder="请输入职务或身份（如：医生、护士、研究员等）">
          </div>
          <div class="form-group">
            <label>所属机构：</label>
            <input type="text" v-model="recorderInfo.institution" placeholder="请输入所属医院或机构名称">
          </div>
          <div class="form-group">
            <label>联系方式：</label>
            <input type="text" v-model="recorderInfo.contact" placeholder="请输入联系电话或邮箱">
          </div>
          <div class="form-group">
            <label>默认备注：</label>
            <textarea v-model="recorderInfo.defaultRemarks" placeholder="请输入默认备注信息（可选）" rows="3"></textarea>
          </div>
        </div>

        <div class="settings-actions">
          <button @click="saveRecorderInfo" class="save-settings-btn">保存设置</button>
          <button @click="closeSettings" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <!-- 记录人信息显示 -->
    <div class="recorder-info-display" v-if="recorderInfo.name && !showSettings && !showResult && !showExport">
      <div class="recorder-card">
        <div class="recorder-main-info">
          <h3>问答编号：{{ recorderInfo.surveyId }}</h3>
          <p>记录人：{{ recorderInfo.name }} | {{ recorderInfo.position }}</p>
          <p v-if="recorderInfo.institution">{{ recorderInfo.institution }}</p>
        </div>
        <div class="recorder-actions">
          <button @click="showSettings = true" class="edit-recorder-btn">编辑</button>
          <button @click="showExportDialog" class="export-btn">{{ surveyConfig.ui.buttons.export }}</button>
        </div>
      </div>
    </div>

    <!-- 导出数据模态框 -->
    <div class="export-modal" v-if="showExport">
      <div class="export-content">
        <div class="export-header">
          <h2>{{ surveyConfig.export.title }}</h2>
          <button @click="closeExport" class="close-btn">×</button>
        </div>

        <div class="export-form">
          <div class="export-info">
            <p><strong>当前问答编号：</strong>{{ recorderInfo.surveyId }}</p>
            <p><strong>导出说明：</strong>将从服务器打包当前编号的所有PSQI睡眠质量评估数据</p>
          </div>

          <div class="form-group">
            <label>导出密码：<span class="required">*</span></label>
            <input type="password" v-model="exportPassword" placeholder="请输入导出密码" @keyup.enter="exportData">
            <p class="field-hint">请联系管理员获取导出密码</p>
          </div>

          <div class="export-options">
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeRawData">
                包含原始评估数据
              </label>
            </div>
            <div class="form-group">
              <label>
                <input type="checkbox" v-model="exportOptions.includeStatistics">
                包含统计分析
              </label>
            </div>
          </div>
        </div>

        <div class="export-actions">
          <button @click="exportData" class="export-confirm-btn" :disabled="!exportPassword">
            <span v-if="!isExporting">导出压缩包</span>
            <span v-else>导出中...</span>
          </button>
          <button @click="closeExport" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>

    <div class="survey-form" v-if="!showResult && !showSettings && !showExport">
      <!-- 被评估人基本信息 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.basicInfo.title }}</h2>
        <div class="form-group" v-for="field in surveyConfig.sections.basicInfo.fields" :key="field.name">
          <label>{{ field.label }}：<span v-if="field.required" class="required">*</span></label>
          <input
            v-if="field.type === 'text' || field.type === 'number' || field.type === 'tel' || field.type === 'datetime-local'"
            :type="field.type" v-model="formData[field.name]" :placeholder="field.placeholder" :min="field.min"
            :max="field.max" :step="field.step">
          <textarea v-else-if="field.type === 'textarea'" v-model="formData[field.name]"
            :placeholder="field.placeholder" :rows="field.rows"></textarea>
          <div v-else-if="field.type === 'radio'" class="radio-group">
            <label v-for="option in field.options" :key="option.value">
              <input type="radio" v-model="formData[field.name]" :value="option.value"> {{ option.label }}
            </label>
          </div>
        </div>
      </div>

      <!-- PSQI睡眠质量评估 -->
      <div class="section">
        <h2>{{ surveyConfig.sections.assessment.title }}</h2>
        <p class="assessment-description">{{ surveyConfig.sections.assessment.description }}</p>

        <!-- 表单组 -->
        <div class="form-groups">
          <div v-for="(group, groupIndex) in surveyConfig.formGroups" :key="group.id" class="form-group-section"
            :class="{ 'active': currentGroupIndex === groupIndex }" v-show="currentGroupIndex === groupIndex">
            <div class="group-header">
              <h3>{{ group.title }}</h3>
              <p v-if="group.description" class="group-description">{{ group.description }}</p>
            </div>

            <div class="questions">
              <div v-for="question in group.questions" :key="question.id" class="question-item" :class="{
                'conditional': question.dependsOn,
                'hidden': !shouldShowQuestion(question)
              }" v-show="shouldShowQuestion(question)">
                <label class="question-label">
                  {{ question.label }}
                  <span v-if="question.required" class="required">*</span>
                </label>

                <!-- 文本输入 -->
                <input v-if="question.type === 'text'" type="text" v-model="formData[question.id]"
                  :placeholder="question.placeholder" class="form-input">

                <!-- 数字输入 -->
                <div v-else-if="question.type === 'number'" class="number-input-group">
                  <input type="number" v-model.number="formData[question.id]" :placeholder="question.placeholder"
                    :min="question.min" :max="question.max" :step="question.step || 1" class="form-input number-input">
                  <span v-if="question.unit" class="input-unit">{{ question.unit }}</span>
                </div>

                <!-- 时间输入 -->
                <input v-else-if="question.type === 'time'" type="time" v-model="formData[question.id]"
                  class="form-input">

                <!-- 日期输入 -->
                <input v-else-if="question.type === 'date'" type="date" v-model="formData[question.id]"
                  class="form-input">

                <!-- 单选按钮 -->
                <div v-else-if="question.type === 'radio'" class="radio-group">
                  <label v-for="option in question.options" :key="option.value" class="radio-option">
                    <input type="radio" :name="question.id" :value="option.value" v-model="formData[question.id]"
                      @change="handleQuestionChange(question.id)">
                    <span class="radio-label">{{ option.label }}</span>
                  </label>
                </div>

                <!-- 文本域 -->
                <textarea v-else-if="question.type === 'textarea'" v-model="formData[question.id]"
                  :placeholder="question.placeholder" class="form-textarea" rows="3"></textarea>
              </div>
            </div>
          </div>
        </div>

        <!-- 导航按钮 -->
        <div class="form-navigation">
          <button v-if="currentGroupIndex > 0" @click="previousGroup" class="nav-btn prev-btn">
            {{ surveyConfig.ui.buttons.previous }}
          </button>

          <div class="progress-indicator">
            <span>{{ currentGroupIndex + 1 }} / {{ surveyConfig.formGroups.length }}</span>
            <div class="progress-bar">
              <div class="progress-fill"
                :style="{ width: ((currentGroupIndex + 1) / surveyConfig.formGroups.length * 100) + '%' }"></div>
            </div>
          </div>

          <button v-if="currentGroupIndex < surveyConfig.formGroups.length - 1" @click="nextGroup"
            class="nav-btn next-btn">
            {{ surveyConfig.ui.buttons.next }}
          </button>

          <button v-if="currentGroupIndex === surveyConfig.formGroups.length - 1" @click="calculateResult"
            class="nav-btn submit-btn" :disabled="!isFormValid">
            {{ surveyConfig.ui.buttons.submit }}
          </button>
        </div>
      </div>
    </div>

    <!-- 结果展示 -->
    <div class="result-section" v-if="showResult">
      <h2>PSQI评估结果</h2>
      <div class="result-card">
        <div class="result-summary">
          <h3>{{ result.diagnosis }}</h3>
          <p class="score">总分：{{ result.totalScore }}/21</p>
        </div>

        <div class="result-details">
          <h4>各组件得分详情：</h4>
          <ul>
            <li v-for="component in result.components" :key="component.name">
              {{ component.name }}：{{ component.score }}/{{ component.maxScore }}
            </li>
          </ul>
        </div>

        <div class="result-explanation">
          <h4>评估说明：</h4>
          <p>{{ result.explanation }}</p>
        </div>

        <div class="action-buttons">
          <button @click="saveToBackendOnly" class="save-btn" :disabled="isSaving">
            <span v-if="!isSaving">{{ surveyConfig.ui.buttons.save || '保存结果' }}</span>
            <span v-else>保存中...</span>
          </button>
          <button @click="resetForm" class="reset-btn">{{ surveyConfig.ui.buttons.restart }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { psqiConfig } from '@/config/psqiConfig.js';
import { calculatePSQIAssessment } from '@/config/psqiLogic.js';

export default {
  name: 'PSQISurvey',
  mounted() {
    // 自动设置当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    this.formData.recordTime = `${year}-${month}-${day}T${hours}:${minutes}`;

    // 加载记录人信息
    this.loadRecorderInfo();

    // 初始化表单数据
    this.initializeForm();
  },
  data() {
    return {
      surveyConfig: psqiConfig,
      showResult: false,
      showSettings: false,
      showExport: false,
      isExporting: false,
      isSaving: false,
      exportPassword: '',
      currentGroupIndex: 0,
      // 记录人信息（设置）
      recorderInfo: {
        surveyId: '',
        name: '',
        position: '',
        institution: '',
        contact: '',
        defaultRemarks: ''
      },
      // 导出选项
      exportOptions: {
        includeRawData: true,
        includeStatistics: true
      },
      // 问卷表单数据
      formData: {},
      result: {
        totalScore: 0,
        diagnosis: '',
        components: {},
        explanation: ''
      }
    }
  },
  computed: {
    isFormValid() {
      // 个人信息字段已改为选填，不再进行必填验证
      return this.recorderInfo.surveyId &&
        this.recorderInfo.name &&
        this.recorderInfo.position;
    }
  },
  methods: {
    // 辅助函数：将空字符串转换为 null（用于整数字段）
    toIntOrNull(value) {
      return value === '' || value === null || value === undefined ? null : value;
    },
    
    // 导航方法
    goToHome() {
      this.$router.push('/');
    },

    // 初始化表单数据
    initializeForm() {
      // 保留已设置的recordTime值
      const existingRecordTime = this.formData.recordTime;

      this.formData = {
        assessment_date: new Date().toISOString().split('T')[0],
        recordTime: existingRecordTime || '' // 保留现有的recordTime
      };

      // 初始化所有字段为空值
      this.surveyConfig.formGroups.forEach(group => {
        group.questions.forEach(question => {
          if (!Object.prototype.hasOwnProperty.call(this.formData, question.id)) {
            this.formData[question.id] = question.type === 'number' ? null : '';
          }
        });
      });
    },

    // 设置相关方法
    saveRecorderInfo() {
      // 验证必填字段
      if (!this.recorderInfo.surveyId || !this.recorderInfo.name || !this.recorderInfo.position) {
        alert('请填写所有必填信息（问答编号、记录人姓名、职务/身份）！');
        return;
      }

      // 保存记录人信息到本地存储
      localStorage.setItem('psqiRecorderInfo', JSON.stringify(this.recorderInfo));
      // 设置默认备注
      if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
        this.formData.remarks = this.recorderInfo.defaultRemarks;
      }
      this.showSettings = false;
      alert('记录人信息已保存！');
    },

    closeSettings() {
      this.showSettings = false;
    },

    loadRecorderInfo() {
      // 从本地存储加载记录人信息
      const saved = localStorage.getItem('psqiRecorderInfo');
      if (saved) {
        this.recorderInfo = JSON.parse(saved);
        // 设置默认备注
        if (this.recorderInfo.defaultRemarks && !this.formData.remarks) {
          this.formData.remarks = this.recorderInfo.defaultRemarks;
        }
      }
    },

    // 导出相关方法
    showExportDialog() {
      this.showExport = true;
      this.exportPassword = '';
    },

    closeExport() {
      this.showExport = false;
      this.exportPassword = '';
      this.isExporting = false;
    },

    async exportData() {
      this.isExporting = true;

      try {
        // 发送导出请求到服务器 - 使用专门的PSQI导出接口
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/export-psqi-survey`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            surveyId: this.recorderInfo.surveyId,
            password: this.exportPassword,
            exportOptions: this.exportOptions
          })
        });

        if (response.status === 401) {
          alert('密码错误，请重新输入！');
          return;
        }

        if (!response.ok) {
          throw new Error('导出请求失败');
        }

        // 获取服务器返回的压缩包
        const blob = await response.blob();

        if (blob.size === 0) {
          alert('当前问答编号下没有PSQI问卷数据！');
          return;
        }

        // 下载服务器生成的压缩包
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `PSQI问卷数据_${this.recorderInfo.surveyId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        alert('数据导出成功！');
        this.closeExport();
      } catch (error) {
        console.error('导出失败:', error);
        alert('导出失败，请检查网络连接或联系管理员！');
      } finally {
        this.isExporting = false;
      }
    },

    // 表单导航方法
    shouldShowQuestion(question) {
      if (!question.dependsOn) return true;

      const dependentValue = this.formData[question.dependsOn];
      if (question.showWhen) {
        return question.showWhen.includes(parseInt(dependentValue));
      }

      // 如果有依赖但没有showWhen，则当依赖字段有值时显示
      return dependentValue !== '' && dependentValue !== null && dependentValue !== undefined;
    },

    handleQuestionChange(questionId) {
      // 当问题答案改变时，清除相关的条件性问题
      this.surveyConfig.formGroups.forEach(group => {
        group.questions.forEach(question => {
          if (question.dependsOn === questionId && !this.shouldShowQuestion(question)) {
            this.formData[question.id] = question.type === 'number' ? null : '';
          }
        });
      });
    },

    nextGroup() {
      if (this.currentGroupIndex < this.surveyConfig.formGroups.length - 1) {
        this.currentGroupIndex++;
      }
    },

    previousGroup() {
      if (this.currentGroupIndex > 0) {
        this.currentGroupIndex--;
      }
    },

    calculateResult() {
      // 使用PSQI评估逻辑
      this.result = calculatePSQIAssessment(this.formData);
      this.showResult = true;
    },

    async saveToBackendOnly() {
      this.isSaving = true;

      try {
        // 1. 保存问卷数据到后台
        await this.saveToBackend();

        // 2. 生成评估报告内容
        const timestamp = new Date().toLocaleString('zh-CN');
        const recordTime = this.formData.recordTime ?
          new Date(this.formData.recordTime).toLocaleString('zh-CN') :
          timestamp;

        const content = `PSQI睡眠质量评估结果报告
问答编号：${this.recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${this.recorderInfo.name}
记录人职务/身份：${this.recorderInfo.position}
所属机构：${this.recorderInfo.institution}
联系方式：${this.recorderInfo.contact}
记录时间：${recordTime}
备注：${this.formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${this.formData.patientName}
年龄：${this.formData.age}岁
性别：${this.formData.gender === 'male' ? '男性' : '女性'}
联系电话：${this.formData.phone || '未填写'}

=== 评估结果 ===
总分：${this.result.totalScore}/21
诊断结果：${this.result.diagnosis}

=== 各组件得分详情 ===
${Object.values(this.result.components).map(component =>
          `${component.name}：${component.score}/${component.maxScore}`
        ).join('\n')}

=== 评估说明 ===
${this.result.explanation}

报告结束
`;

        // 3. 保存评估报告到@data/文件夹
        await this.saveFileToDataFolder(content);

        alert('✅ 数据已成功保存到后台！\n\n📁 问卷数据：survey_data/\n📄 评估报告：@data/');

      } catch (error) {
        console.error('保存到后台失败:', error);
        alert('❌ 保存失败，请检查网络连接或联系管理员！\n\n错误信息：' + error.message);
      } finally {
        this.isSaving = false;
      }
    },

    async saveToBackend() {
      // 构建符合PSQISurveyData模型的数据格式
      const surveyData = {
        surveyId: this.recorderInfo.surveyId,
        recordTime: new Date().toISOString(),
        recorderName: this.recorderInfo.name,
        recorderPosition: this.recorderInfo.position,
        recorderInstitution: this.recorderInfo.institution,
        recorderContact: this.recorderInfo.contact,
        patientName: this.formData.patientName || "未填写",
        age: (this.formData.age !== null && this.formData.age !== undefined && this.formData.age !== '') ? parseInt(this.formData.age) : 0,
        gender: this.formData.gender,
        phone: this.formData.phone,
        remarks: this.formData.remarks,
        assessmentDate: this.formData.assessment_date,
        // 原始问卷字段 - 保持原始字段名用于CSV生成
        SL01: this.formData.SL01,
        SL02: this.toIntOrNull(this.formData.SL02),
        SL03: this.formData.SL03,
        SL04: this.formData.SL04,
        SL051: this.toIntOrNull(this.formData.SL051),
        SL052: this.toIntOrNull(this.formData.SL052),
        SL053: this.toIntOrNull(this.formData.SL053),
        SL054: this.toIntOrNull(this.formData.SL054),
        SL055: this.toIntOrNull(this.formData.SL055),
        SL056: this.toIntOrNull(this.formData.SL056),
        SL057: this.toIntOrNull(this.formData.SL057),
        SL058: this.toIntOrNull(this.formData.SL058),
        SL059: this.toIntOrNull(this.formData.SL059),
        SL05X: this.formData.SL05X_description,
        SL05X1: this.toIntOrNull(this.formData.SL05X1),
        SL06: this.toIntOrNull(this.formData.SL06),
        SL07: this.toIntOrNull(this.formData.SL07),
        SL08: this.toIntOrNull(this.formData.SL08),
        SL09: this.toIntOrNull(this.formData.SL09),
        SL10: this.toIntOrNull(this.formData.SL10),
        SL101: this.toIntOrNull(this.formData.SL101),
        SL102: this.toIntOrNull(this.formData.SL102),
        SL103: this.toIntOrNull(this.formData.SL103),
        SL104: this.toIntOrNull(this.formData.SL104),
        SL10X: this.formData.SL10X_description,
        SL105: this.toIntOrNull(this.formData.SL105),
        // 计算结果
        totalScore: this.result.totalScore,
        maxScore: 21,
        subjective_sleep_quality: this.result.components.subjective_sleep_quality?.score,
        sleep_latency: this.result.components.sleep_latency?.score,
        sleep_duration: this.result.components.sleep_duration?.score,
        sleep_efficiency: this.result.components.sleep_efficiency?.score,
        sleep_disturbance: this.result.components.sleep_disturbances?.score,
        sleep_medication: this.result.components.sleep_medication?.score,
        daytime_dysfunction: this.result.components.daytime_dysfunction?.score,
        diagnosis: this.result.diagnosis,
        createdAt: new Date().toISOString()
      };

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-psqi-survey`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(surveyData)
      });

      if (!response.ok) {
        throw new Error('保存问卷数据失败');
      }
    },

    async saveFileToDataFolder(content) {
      // 通过API保存文件到@data/文件夹
      const filename = `PSQI睡眠质量评估结果_${this.recorderInfo.surveyId}_${this.formData.patientName}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`;

      const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/save-file`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          filename: filename,
          content: content,
          surveyId: this.recorderInfo.surveyId
        })
      });

      if (!response.ok) {
        throw new Error('保存评估报告失败');
      }
    },

    resetForm() {
      this.formData = {};
      this.result = {
        totalScore: 0,
        diagnosis: '',
        components: {},
        explanation: ''
      };
      this.showResult = false;
      this.currentGroupIndex = 0;
      this.initializeForm();
    }
  }
}
</script>

<style scoped>
.psqi-survey {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 2.5em;
  font-weight: 300;
}

.subtitle {
  margin: 0 0 20px 0;
  font-size: 1.2em;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.home-btn,
.settings-btn {
  padding: 10px 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.home-btn:hover,
.settings-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
}

/* 设置模态框样式 */
.settings-modal,
.export-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.settings-content,
.export-content {
  background: white;
  padding: 30px;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.settings-header,
.export-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 5px;
  border-radius: 50%;
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: #f0f0f0;
  color: #333;
}

/* 记录人信息显示 */
.recorder-info-display {
  margin-bottom: 30px;
}

.recorder-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 4px solid #667eea;
}

.recorder-main-info h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.recorder-main-info p {
  margin: 5px 0;
  color: #666;
}

.recorder-actions {
  display: flex;
  gap: 10px;
}

.edit-recorder-btn,
.export-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.edit-recorder-btn:hover {
  background: #f0f0f0;
}

.export-btn {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.export-btn:hover {
  background: #218838;
}

/* 表单样式 */
.section {
  background: white;
  padding: 30px;
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.section h2 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 1.8em;
  border-bottom: 2px solid #667eea;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #dc3545;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.field-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.radio-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.radio-option:hover {
  border-color: #667eea;
  background: #f8f9ff;
}

.radio-option input[type="radio"] {
  width: auto;
}

/* 表单组导航 */
.form-group-section {
  margin-bottom: 30px;
}

.group-header h3 {
  color: #667eea;
  margin-bottom: 10px;
}

.group-description {
  color: #666;
  font-style: italic;
  margin-bottom: 20px;
}

.question-item {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-label {
  font-weight: 500;
  margin-bottom: 10px;
  display: block;
}

.number-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-unit {
  color: #666;
  font-size: 14px;
}

.form-navigation {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 10px;
}

.nav-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.prev-btn {
  background: #6c757d;
  color: white;
}

.prev-btn:hover {
  background: #5a6268;
}

.next-btn,
.submit-btn {
  background: #667eea;
  color: white;
}

.next-btn:hover,
.submit-btn:hover {
  background: #5a67d8;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.progress-indicator {
  text-align: center;
}

.progress-bar {
  width: 200px;
  height: 8px;
  background: #e1e5e9;
  border-radius: 4px;
  margin-top: 5px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #667eea;
  transition: width 0.3s ease;
}

/* 结果展示样式 */
.result-section {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.result-card {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 10px;
  border-left: 4px solid #28a745;
}

.result-summary {
  text-align: center;
  margin-bottom: 25px;
}

.result-summary h3 {
  color: #28a745;
  margin-bottom: 10px;
  font-size: 1.5em;
}

.score {
  font-size: 1.2em;
  font-weight: bold;
  color: #333;
}

.result-details ul {
  list-style: none;
  padding: 0;
}

.result-details li {
  padding: 8px 0;
  border-bottom: 1px solid #e1e5e9;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 25px;
}

.save-btn,
.reset-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
}

.save-btn {
  background: #28a745;
  color: white;
}

.save-btn:hover {
  background: #218838;
}

.save-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.reset-btn {
  background: #6c757d;
  color: white;
}

.reset-btn:hover {
  background: #5a6268;
}

/* 设置和导出按钮样式 */
.settings-actions,
.export-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
  margin-top: 25px;
}

.save-settings-btn,
.export-confirm-btn {
  background: #667eea;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.save-settings-btn:hover,
.export-confirm-btn:hover {
  background: #5a67d8;
}

.export-confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  background: #6c757d;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #5a6268;
}

.export-info {
  background: #e7f3ff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #007bff;
}

.export-options {
  margin: 20px 0;
}

.export-options .form-group {
  margin-bottom: 10px;
}

.export-options label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.export-options input[type="checkbox"] {
  width: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .psqi-survey {
    padding: 10px;
  }

  .header h1 {
    font-size: 2em;
  }

  .header-actions {
    flex-direction: column;
    gap: 10px;
  }

  .settings-content,
  .export-content {
    width: 95%;
    padding: 20px;
  }

  .recorder-card {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .form-navigation {
    flex-direction: column;
    gap: 15px;
  }

  .progress-indicator {
    order: -1;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>